home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.004 / xemacs-1 / xemacs-19.13 / lisp / utils / mail-extr.el < prev    next >
Encoding:
Text File  |  1995-03-25  |  65.1 KB  |  1,902 lines

  1. ;;; mail-extr.el --- extract full name and address from RFC 822 mail header.
  2.  
  3. ;; Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Joe Wells <jbw@cs.bu.edu>
  6. ;; Maintainer: Jamie Zawinski <jwz@lucid.com>
  7. ;; Version: 1.8
  8. ;; Keywords: mail
  9.  
  10. ;; This file is part of XEmacs.
  11.  
  12. ;; XEmacs is free software; you can redistribute it and/or modify it
  13. ;; under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation; either version 2, or (at your option)
  15. ;; any later version.
  16.  
  17. ;; XEmacs is distributed in the hope that it will be useful, but
  18. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  20. ;; General Public License for more details.
  21.  
  22. ;; You should have received a copy of the GNU General Public License
  23. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  24. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  25.  
  26. ;;; Commentary:
  27.  
  28. ;; The entry point of this code is
  29. ;;
  30. ;;    mail-extract-address-components: (address)
  31. ;;  
  32. ;;    Given an RFC-822 ADDRESS, extract full name and canonical address.
  33. ;;    Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).
  34. ;;    If no name can be extracted, FULL-NAME will be nil.
  35. ;;    ADDRESS may be a string or a buffer.  If it is a buffer, the visible 
  36. ;;     (narrowed) portion of the buffer will be interpreted as the address.
  37. ;;     (This feature exists so that the clever caller might be able to avoid
  38. ;;     consing a string.)
  39. ;;    If ADDRESS contains more than one RFC-822 address, only the first is
  40. ;;     returned.
  41. ;;
  42. ;; This code is more correct (and more heuristic) parser than the code in
  43. ;; rfc822.el.  And despite its size, it's fairly fast.
  44. ;;
  45. ;; There are two main benefits:
  46. ;;
  47. ;; 1. Higher probability of getting the correct full name for a human than
  48. ;;    any other package we know of.  (On the other hand, it will cheerfully
  49. ;;    mangle non-human names/comments.)
  50. ;; 2. Address part is put in a canonical form.
  51. ;;
  52. ;; The interface is not yet carved in stone; please give us suggestions.
  53. ;;
  54. ;; We have an extensive test-case collection of funny addresses if you want to
  55. ;; work with the code.  Developing this code requires frequent testing to
  56. ;; make sure you're not breaking functionality.  The test cases aren't included
  57. ;; because they are over 100K.
  58. ;;
  59. ;; If you find an address that mail-extr fails on, please send it to the 
  60. ;; maintainer along with what you think the correct results should be.  We do
  61. ;; not consider it a bug if mail-extr mangles a comment that does not
  62. ;; correspond to a real human full name, although we would prefer that 
  63. ;; mail-extr would return the comment as-is.
  64. ;;
  65. ;; Features:
  66. ;;
  67. ;; * Full name handling:
  68. ;;
  69. ;;   * knows where full names can be found in an address.
  70. ;;   * avoids using empty comments and quoted text.
  71. ;;   * extracts full names from mailbox names.
  72. ;;   * recognizes common formats for comments after a full name.
  73. ;;   * puts a period and a space after each initial.
  74. ;;   * understands & referring to the mailbox name, capitalized.
  75. ;;   * strips name prefixes like "Prof.", etc.
  76. ;;   * understands what characters can occur in names (not just letters).
  77. ;;   * figures out middle initial from mailbox name.
  78. ;;   * removes funny nicknames.
  79. ;;   * keeps suffixes such as Jr., Sr., III, etc.
  80. ;;   * reorders "Last, First" type names.
  81. ;;
  82. ;; * Address handling:
  83. ;;
  84. ;;   * parses rfc822 quoted text, comments, and domain literals.
  85. ;;   * parses rfc822 multi-line headers.
  86. ;;   * does something reasonable with rfc822 GROUP addresses.
  87. ;;   * handles many rfc822 noncompliant and garbage addresses.
  88. ;;   * canonicalizes addresses (after stripping comments/phrases outside <>).
  89. ;;     * converts ! addresses into .UUCP and %-style addresses.
  90. ;;     * converts rfc822 ROUTE addresses to %-style addresses.
  91. ;;     * truncates %-style addresses at leftmost fully qualified domain name.
  92. ;;     * handles local relative precedence of ! vs. % and @ (untested).
  93. ;;
  94. ;; It does almost no string creation.  It primarily uses the built-in
  95. ;; parsing routines with the appropriate syntax tables.  This should
  96. ;; result in greater speed.
  97. ;;
  98. ;; TODO:
  99. ;;
  100. ;; * handle all test cases.  (This will take forever.)
  101. ;; * software to pick the correct header to use (eg., "Senders-Name:").
  102. ;; * multiple addresses in the "From:" header (almost all of the necessary
  103. ;;   code is there).
  104. ;; * flag to not treat `,' as an address separator.  (This is useful when
  105. ;;   there is a "From:" header but no "Sender:" header, because then there
  106. ;;   is only allowed to be one address.)
  107. ;; * mailbox name does not necessarily contain full name.
  108. ;; * fixing capitalization when it's all upper or lowercase.  (Hard!)
  109. ;; * some of the domain literal handling is missing.  (But I've never even
  110. ;;   seen one of these in a mail address, so maybe no big deal.)
  111. ;; * arrange to have syntax tables byte-compiled.
  112. ;; * speed hacks.
  113. ;; * delete unused variables.
  114. ;; * arrange for testing with different relative precedences of ! vs. @
  115. ;;   and %.
  116. ;; * insert documentation strings!
  117. ;; * handle X.400-gatewayed addresses according to RFC 1148.
  118.  
  119. ;;; Change Log: 
  120. ;; 
  121. ;; Thu Feb 17 17:57:33 1994  Jamie Zawinski (jwz@lucid.com)
  122. ;;
  123. ;;    * merged with jbw's latest version
  124. ;;
  125. ;; Wed Feb  9 21:56:27 1994  Jamie Zawinski (jwz@lucid.com)
  126. ;;
  127. ;;      * high-bit chars in comments weren't treated as word syntax
  128. ;;
  129. ;; Sat Feb  5 03:13:40 1994  Jamie Zawinski (jwz@lucid.com)
  130. ;;
  131. ;;      * call replace-match with fixed-case arg
  132. ;;
  133. ;; Thu Dec 16 21:56:45 1993  Jamie Zawinski (jwz@lucid.com)
  134. ;;
  135. ;;      * some more cleanup, doc, added provide
  136. ;;
  137. ;; Tue Mar 23 21:23:18 1993  Joe Wells  (jbw at csd.bu.edu)
  138. ;; 
  139. ;;     * Made mail-full-name-prefixes a user-customizable variable.
  140. ;;        Allow passing the address as a buffer as well as as a string.
  141. ;;        Allow [ and ] as name characters (Finnish character set).
  142. ;; 
  143. ;; Mon Mar 22 21:20:56 1993  Joe Wells  (jbw at bigbird.bu.edu)
  144. ;; 
  145. ;;     * Handle "null" addresses.  Handle = used for spacing in mailbox
  146. ;;       name.  Fix bug in handling of ROUTE-ADDR-type addresses that are
  147. ;;       missing their brackets.  Handle uppercase "JR".  Extract full
  148. ;;       names from X.400 addresses encoded in RFC-822.  Fix bug in
  149. ;;        handling of multiple addresses where first has trailing comment.
  150. ;;        Handle more kinds of telephone extension lead-ins.
  151. ;; 
  152. ;; Mon Mar 22 20:16:57 1993  Joe Wells  (jbw at bigbird.bu.edu)
  153. ;; 
  154. ;;     * Handle HZ encoding for embedding GB encoded chinese characters.
  155. ;; 
  156. ;; Mon Mar 22 00:46:12 1993  Joe Wells  (jbw at bigbird.bu.edu)
  157. ;; 
  158. ;;     * Fixed too broad matching of ham radio call signs.  Fixed bug in
  159. ;;       handling an unmatched ' in a name string.  Enhanced recognition
  160. ;;       of when . in the mailbox name terminates the name portion.
  161. ;;       Narrowed conversion of . to space to only the necessary
  162. ;;       situation.  Deal with VMS's stupid date stamps.  Handle a unique
  163. ;;       way of introducing an alternate address.  Fixed spacing bug I
  164. ;;       introduced in switching last name order.  Fixed bug in handling
  165. ;;       address with ! and % but no @.  Narrowed the cases in which
  166. ;;       certain trailing words are discarded.
  167. ;; 
  168. ;; Sun Mar 21 21:41:06 1993  Joe Wells  (jbw at bigbird.bu.edu)
  169. ;; 
  170. ;;     * Fixed bugs in handling GROUP addresses.  Certain words in the
  171. ;;       middle of a name no longer terminate it.  Handle LISTSERV list
  172. ;;        names.  Ignore comment field containing mailbox name.
  173. ;; 
  174. ;; Sun Mar 21 14:39:38 1993  Joe Wells  (jbw at bigbird.bu.edu)
  175. ;; 
  176. ;;     * Moved variant-method code back into main function.  Handle
  177. ;;     underscores as spaces in comments.  Handle leading nickname.  Add
  178. ;;     flag to ignore single-word names.  Other changes.
  179. ;; 
  180. ;; Mon Feb  1 22:23:31 1993  Joe Wells  (jbw at bigbird.bu.edu)
  181. ;; 
  182. ;;     * Added in changes by Rod Whitby and Jamie Zawinski.  This
  183. ;;        includes the flag mail-extr-guess-middle-initial and the fix for
  184. ;;        handling multiple addresses correctly.
  185. ;; 
  186. ;; Mon Apr  6 23:59:09 1992  Joe Wells  (jbw at bigbird.bu.edu)
  187. ;; 
  188. ;;     * Cleaned up some more.  Release version 1.0 to world.
  189. ;; 
  190. ;; Sun Apr  5 19:39:08 1992  Joe Wells  (jbw at bigbird.bu.edu)
  191. ;; 
  192. ;;     * Cleaned up full name extraction extensively.
  193. ;; 
  194. ;; Sun Feb  2 14:45:24 1992  Joe Wells  (jbw at bigbird.bu.edu)
  195. ;; 
  196. ;;     * Total rewrite.  Integrated mail-canonicalize-address into
  197. ;;     mail-extract-address-components.  Now handles GROUP addresses more
  198. ;;     or less correctly.  Better handling of lots of different cases.
  199. ;; 
  200. ;; Fri Jun 14 19:39:50 1991
  201. ;;    * Created.
  202.  
  203. ;;; Code:
  204.  
  205.  
  206. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  207. ;;
  208. ;; User configuration variable definitions.
  209. ;;
  210.  
  211. (defvar mail-extr-guess-middle-initial nil
  212.   "*Whether to try to guess middle initial from mail address.
  213. If true, then when we see an address like \"John Smith <jqs@host.com>\"
  214. we will assume that \"John Q. Smith\" is the fellow's name.")
  215.  
  216. (defvar mail-extr-ignore-single-names t
  217.   "*Whether to ignore a name that is just a single word.
  218. If true, then when we see an address like \"Idiot <dumb@stupid.com>\"
  219. we will act as though we couldn't find a full name in the address.")
  220.  
  221. ;; Matches a leading title that is not part of the name (does not
  222. ;; contribute to uniquely identifying the person).
  223. (defvar mail-extr-full-name-prefixes
  224.   (purecopy
  225.    "\\(Prof\\|D[Rr]\\|Mrs?\\|Rev\\|Rabbi\\|SysOp\\|LCDR\\)\\.?[ \t\n]")
  226.   "*Matches prefixes to the full name that identify a person's position.
  227. These are stripped from the full name because they do not contribute to
  228. uniquely identifying the person.")
  229.  
  230. (defvar mail-extr-@-binds-tighter-than-! nil
  231.   "*Whether the local mail transport agent looks at ! before @.")
  232.  
  233. (defvar mail-extr-mangle-uucp nil
  234.   "*Whether to throw away information in UUCP addresses
  235. by translating things like \"foo!bar!baz@host\" into \"baz@bar.UUCP\".")
  236.  
  237. ;;----------------------------------------------------------------------
  238. ;; what orderings are meaningful?????
  239. ;;(defvar mail-operator-precedence-list '(?! ?% ?@))
  240. ;; Right operand of a % or a @ must be a domain name, period.  No other
  241. ;; operators allowed.  Left operand of a @ is an address relative to that
  242. ;; site.
  243.  
  244. ;; Left operand of a ! must be a domain name.  Right operand is an
  245. ;; arbitrary address.
  246. ;;----------------------------------------------------------------------
  247.  
  248.  
  249.  
  250. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  251. ;;
  252. ;; Constant definitions.
  253. ;;
  254.  
  255. ;;           Codes in
  256. ;; Names in  ISO 8859-1 Name
  257. ;; ISO 10XXX ISO 8859-2 in
  258. ;; ISO 6937  ISO 10646  RFC            Swedish
  259. ;; etc.      Hex Oct    1345 TeX Split ASCII Description
  260. ;; --------- ---------- ---- --- ----- ----- -------------------------------
  261. ;; %a        E4  344    a:   \"a ae    {     latin small   a + diaeresis   Σ
  262. ;; %o        F6  366    o:   \"o oe    |     latin small   o + diaeresis   ÷
  263. ;; @a        E5  345    aa   \oa aa    }     latin small   a + ring above  σ
  264. ;; %u        FC  374    u:   \"u ue    ~     latin small   u + diaeresis   ⁿ
  265. ;; /e        E9  351    e'   \'e       `     latin small   e + acute       Θ
  266. ;; %A        C4  304    A:   \"A AE    [     latin capital a + diaeresis   ─
  267. ;; %O        D6  326    O:   \"O OE    \     latin capital o + diaeresis   ╓
  268. ;; @A        C5  305    AA   \oA AA    ]     latin capital a + ring above  ┼
  269. ;; %U        DC  334    U:   \"U UE    ^     latin capital u + diaeresis   ▄
  270. ;; /E        C9  311    E'   \'E       @     latin capital e + acute       ╔
  271.  
  272. ;; NOTE: @a and @A are not in ISO 8859-2 (the codes mentioned above invoke
  273. ;; /l and /L).  Some of this data was retrieved from
  274. ;; listserv@jhuvm.hcf.jhu.edu.
  275.  
  276. ;; Any character that can occur in a name, not counting characters that
  277. ;; separate parts of a multipart name (hyphen and period).
  278. ;; Yes, there are weird people with digits in their names.
  279. ;; You will also notice the consideration for the
  280. ;; Swedish/Finnish/Norwegian character set.
  281. ;; #### (go to \376 instead of \377 to work around bug in search.c...)
  282. (defconst mail-extr-all-letters-but-separators
  283.   (purecopy "][A-Za-z{|}'~0-9`\200-\376"))
  284.  
  285. ;; Any character that can occur in a name in an RFC822 address including
  286. ;; the separator (hyphen and possibly period) for multipart names.
  287. ;; #### should . be in here?
  288. (defconst mail-extr-all-letters
  289.   (purecopy (concat mail-extr-all-letters-but-separators "---")))
  290.  
  291. ;; Any character that can start a name.
  292. ;; Keep this set as minimal as possible.
  293. (defconst mail-extr-first-letters (purecopy "A-Za-z"))
  294.  
  295. ;; Any character that can end a name.
  296. ;; Keep this set as minimal as possible.
  297. (defconst mail-extr-last-letters (purecopy "[A-Za-z`'."))
  298.  
  299. (defconst mail-extr-leading-garbage
  300.   (purecopy (format "[^%s]+" mail-extr-first-letters)))
  301.  
  302. ;; (defconst mail-extr-non-name-chars 
  303. ;;   (purecopy (concat "^" mail-extr-all-letters ".")))
  304. ;; (defconst mail-extr-non-begin-name-chars
  305. ;;   (purecopy (concat "^" mail-extr-first-letters)))
  306. ;; (defconst mail-extr-non-end-name-chars
  307. ;;   (purecopy (concat "^" mail-extr-last-letters)))
  308.  
  309. ;; Matches an initial not followed by both a period and a space. 
  310. ;; (defconst mail-extr-bad-initials-pattern
  311. ;;   (purecopy 
  312. ;;    (format "\\(\\([^%s]\\|\\`\\)[%s]\\)\\(\\.\\([^ ]\\)\\| \\|\\([^%s .]\\)\\|\\'\\)"
  313. ;;            mail-extr-all-letters mail-extr-first-letters mail-extr-all-letters)))
  314.  
  315. ;; Matches periods used instead of spaces.  Must not match the period
  316. ;; following an initial.
  317. (defconst mail-extr-bad-dot-pattern
  318.   (purecopy
  319.    (format "\\([%s][%s]\\)\\.+\\([%s]\\)"
  320.        mail-extr-all-letters
  321.        mail-extr-last-letters
  322.        mail-extr-first-letters)))
  323.  
  324. ;; Matches an embedded or leading nickname that should be removed.
  325. ;; (defconst mail-extr-nickname-pattern
  326. ;;   (purecopy
  327. ;;    (format "\\([ .]\\|\\`\\)[\"'`\[\(]\\([ .%s]+\\)[\]\"'\)] "
  328. ;;            mail-extr-all-letters)))
  329.  
  330. ;; Matches the occurrence of a generational name suffix, and the last
  331. ;; character of the preceding name.  This is important because we want to
  332. ;; keep such suffixes: they help to uniquely identify the person.
  333. ;; *** Perhaps this should be a user-customizable variable.  However, the
  334. ;; *** regular expression is fairly tricky to alter, so maybe not.
  335. (defconst mail-extr-full-name-suffix-pattern
  336.   (purecopy
  337.    (format
  338.     "\\(,? ?\\([JjSs][Rr]\\.?\\|V?I+V?\\)\\)\\([^%s]\\([^%s]\\|\\'\\)\\|\\'\\)"
  339.     mail-extr-all-letters mail-extr-all-letters)))
  340.  
  341. (defconst mail-extr-roman-numeral-pattern (purecopy "V?I+V?\\b"))
  342.  
  343. ;; Matches a trailing uppercase (with other characters possible) acronym.
  344. ;; Must not match a trailing uppercase last name or trailing initial
  345. (defconst mail-extr-weird-acronym-pattern
  346.   (purecopy "\\([A-Z]+[-_/]\\|[A-Z][A-Z][A-Z]?\\b\\)"))
  347.       
  348. ;; Matches a mixed-case or lowercase name (not an initial).
  349. ;; #### Match Latin1 lower case letters here too?
  350. ;; (defconst mail-extr-mixed-case-name-pattern
  351. ;;   (purecopy
  352. ;;    (format
  353. ;;     "\\b\\([a-z][%s]*[%s]\\|[%s][%s]*[a-z][%s]*[%s]\\|[%s][%s]*[a-z]\\)"
  354. ;;     mail-extr-all-letters mail-extr-last-letters
  355. ;;     mail-extr-first-letters mail-extr-all-letters mail-extr-all-letters
  356. ;;     mail-extr-last-letters mail-extr-first-letters mail-extr-all-letters)))
  357.  
  358. ;; Matches a trailing alternative address.
  359. ;; #### Match Latin1 letters here too?
  360. ;; #### Match _ before @ here too?  
  361. (defconst mail-extr-alternative-address-pattern
  362.   (purecopy "\\(aka *\\)?[a-zA-Z.]+[!@][a-zA-Z.]"))
  363.  
  364. ;; Matches a variety of trailing comments not including comma-delimited
  365. ;; comments.
  366. (defconst mail-extr-trailing-comment-start-pattern
  367.   (purecopy " [-{]\\|--\\|[+@#></\;]"))
  368.  
  369. ;; Matches a name (not an initial).
  370. ;; This doesn't force a word boundary at the end because sometimes a
  371. ;; comment is separated by a `-' with no preceding space.
  372. (defconst mail-extr-name-pattern
  373.   (purecopy (format "\\b[%s][%s]*[%s]"
  374.             mail-extr-first-letters
  375.             mail-extr-all-letters
  376.             mail-extr-last-letters)))
  377.  
  378. (defconst mail-extr-initial-pattern
  379.   (purecopy (format "\\b[%s]\\([. ]\\|\\b\\)" mail-extr-first-letters)))
  380.  
  381. ;; Matches a single name before a comma.
  382. ;; (defconst mail-extr-last-name-first-pattern
  383. ;;   (purecopy (concat "\\`" mail-extr-name-pattern ",")))
  384.  
  385. ;; Matches telephone extensions.
  386. (defconst mail-extr-telephone-extension-pattern
  387.   (purecopy
  388.    "\\(\\([Ee]xt\\|\\|[Tt]ph\\|[Tt]el\\|[Xx]\\).?\\)? *\\+?[0-9][- 0-9]+"))
  389.  
  390. ;; Matches ham radio call signs.
  391. ;; Help from: Mat Maessen N2NJZ <maessm@rpi.edu>, Mark Feit
  392. ;; <mark@era.com>, Michael Covington <mcovingt@ai.uga.edu>.
  393. ;; Examples: DX504 DX515 K5MRU K8DHK KA9WGN KA9WGN KD3FU KD6EUI KD6HBW
  394. ;; KE9TV KF0NV N1API N3FU N3GZE N3IGS N4KCC N7IKQ N9HHU W4YHF W6ANK WA2SUH
  395. ;; WB7VZI N2NJZ NR3G KJ4KK AB4UM AL7NI KH6OH WN3KBT N4TMI W1A N0NZO
  396. (defconst mail-extr-ham-call-sign-pattern
  397.   (purecopy "\\b\\(DX[0-9]+\\|[AKNW][A-Z]?[0-9][A-Z][A-Z]?[A-Z]?\\)"))
  398.  
  399. ;; Possible trailing suffixes: "\\(/\\(KT\\|A[AEG]\\|[R0-9]\\)\\)?"
  400. ;; /KT == Temporary Technician (has CSC but not "real" license)
  401. ;; /AA == Temporary Advanced
  402. ;; /AE == Temporary Extra
  403. ;; /AG == Temporary General
  404. ;; /R  == repeater
  405. ;; /#  == stations operating out of home district
  406. ;; I don't include these in the regexp above because I can't imagine
  407. ;; anyone putting them with their name in an e-mail address.
  408.  
  409. ;; Matches normal single-part name
  410. (defconst mail-extr-normal-name-pattern
  411.   (purecopy (format "\\b[%s][%s]+[%s]"
  412.             mail-extr-first-letters
  413.             mail-extr-all-letters-but-separators
  414.             mail-extr-last-letters)))
  415.  
  416. ;; Matches a single word name.
  417. ;; (defconst mail-extr-one-name-pattern
  418. ;;   (purecopy (concat "\\`" mail-extr-normal-name-pattern "\\'")))
  419.   
  420. ;; Matches normal two names with missing middle initial
  421. ;; The first name is not allowed to have a hyphen because this can cause
  422. ;; false matches where the "middle initial" is actually the first letter
  423. ;; of the second part of the first name.
  424. (defconst mail-extr-two-name-pattern
  425.   (purecopy
  426.    (concat "\\`\\(" mail-extr-normal-name-pattern
  427.        "\\|" mail-extr-initial-pattern
  428.        "\\) +\\(" mail-extr-name-pattern "\\)\\(,\\|\\'\\)")))
  429.  
  430. (defconst mail-extr-listserv-list-name-pattern
  431.   (purecopy "Multiple recipients of list \\([-A-Z]+\\)"))
  432.  
  433. (defconst mail-extr-stupid-vms-date-stamp-pattern
  434.   (purecopy
  435.    "[0-9][0-9]-[JFMASOND][aepuco][nbrylgptvc]-[0-9][0-9][0-9][0-9] [0-9]+ *"))
  436.  
  437. ;;; HZ -- GB (PRC Chinese character encoding) in ASCII embedding protocol
  438. ;;
  439. ;; In ASCII mode, a byte is interpreted as an ASCII character, unless a '~' is
  440. ;; encountered. The character '~' is an escape character. By convention, it
  441. ;; must be immediately followed ONLY by '~', '{' or '\n' (<LF>), with the
  442. ;; following special meaning.
  443. ;; 
  444. ;; o The escape sequence '~~' is interpreted as a '~'.
  445. ;; o The escape-to-GB sequence '~{' switches the mode from ASCII to GB.
  446. ;; o The escape sequence '~\n' is a line-continuation marker to be consumed
  447. ;;   with no output produced.
  448. ;; 
  449. ;; In GB mode, characters are interpreted two bytes at a time as (pure) GB
  450. ;; codes until the escape-from-GB code '~}' is read. This code switches the
  451. ;; mode from GB back to ASCII.  (Note that the escape-from-GB code '~}'
  452. ;; ($7E7D) is outside the defined GB range.)
  453. (defconst mail-extr-hz-embedded-gb-encoded-chinese-pattern
  454.   (purecopy "~{\\([^~].\\|~[^\}]\\)+~}"))
  455.  
  456. ;; The leading optional lowercase letters are for a bastardized version of
  457. ;; the encoding, as is the optional nature of the final slash.
  458. (defconst mail-extr-x400-encoded-address-pattern
  459.   (purecopy "[a-z]?[a-z]?\\(/[A-Za-z]+\\(\\.[A-Za-z]+\\)?=[^/]+\\)+/?\\'"))
  460.  
  461. (defconst mail-extr-x400-encoded-address-field-pattern-format
  462.   (purecopy "/%s=\\([^/]+\\)\\(/\\|\\'\\)"))
  463.  
  464. (defconst mail-extr-x400-encoded-address-surname-pattern
  465.   ;; S stands for Surname (family name).
  466.   (purecopy
  467.    (format mail-extr-x400-encoded-address-field-pattern-format "[Ss]")))
  468.  
  469. (defconst mail-extr-x400-encoded-address-given-name-pattern
  470.   ;; G stands for Given name.
  471.   (purecopy
  472.    (format mail-extr-x400-encoded-address-field-pattern-format "[Gg]")))
  473.  
  474. (defconst mail-extr-x400-encoded-address-full-name-pattern
  475.   ;; PN stands for Personal Name.  When used it represents the combination
  476.   ;; of the G and S fields.
  477.   ;; "The one system I used having this field asked it with the prompt
  478.   ;; `Personal Name'.  But they mapped it into G and S on outgoing real
  479.   ;; X.400 addresses.  As they mapped G and S into PN on incoming..."
  480.   (purecopy
  481.    (format mail-extr-x400-encoded-address-field-pattern-format "[Pp][Nn]")))
  482.  
  483.  
  484.  
  485. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  486. ;;
  487. ;; Syntax tables used for quick parsing.
  488. ;;
  489.  
  490. (defconst mail-extr-address-syntax-table (make-syntax-table))
  491. (defconst mail-extr-address-comment-syntax-table (make-syntax-table))
  492. (defconst mail-extr-address-domain-literal-syntax-table (make-syntax-table))
  493. (defconst mail-extr-address-text-comment-syntax-table (make-syntax-table))
  494. (defconst mail-extr-address-text-syntax-table (make-syntax-table))
  495. (mapcar
  496.  (function
  497.   (lambda (pair)
  498.     (let ((syntax-table (symbol-value (car pair))))
  499.       (mapcar
  500.        (function
  501.     (lambda (item)
  502.       (if (eq 2 (length item))
  503.           ;; modifying syntax of a single character
  504.           (modify-syntax-entry (car item) (car (cdr item)) syntax-table)
  505.         ;; modifying syntax of a range of characters
  506.         (let ((char (nth 0 item))
  507.           (bound (nth 1 item))
  508.           (syntax (nth 2 item)))
  509.           (while (<= char bound)
  510.         (modify-syntax-entry char syntax syntax-table)
  511.         (setq char (1+ char)))))))
  512.        (cdr pair)))))
  513.  '((mail-extr-address-syntax-table
  514.     (?\000 ?\037 "w")            ;control characters
  515.     (?\040     " ")            ;SPC
  516.     (?! ?~     "w")            ;printable characters
  517.     (?\177     "w")            ;DEL
  518.     (?\200 ?\377 "w")            ;high-bit-on characters
  519.     (?\240     " ")            ;nobreakspace
  520.     (?\t " ")
  521.     (?\r " ")
  522.     (?\n " ")
  523.     (?\( ".")
  524.     (?\) ".")
  525.     (?<  ".")
  526.     (?>  ".")
  527.     (?@  ".")
  528.     (?,  ".")
  529.     (?\; ".")
  530.     (?:  ".")
  531.     (?\\ "\\")
  532.     (?\" "\"")
  533.     (?.  ".")
  534.     (?\[ ".")
  535.     (?\] ".")
  536.     ;; % and ! aren't RFC822 characters, but it is convenient to pretend
  537.     (?%  ".")
  538.     (?!  ".") ;; this needs to be word-constituent when not in .UUCP mode
  539.     )
  540.    (mail-extr-address-comment-syntax-table
  541.     (?\000 ?\377 "w")
  542.     (?\040 " ")
  543.     (?\240 " ")
  544.     (?\t " ")
  545.     (?\r " ")
  546.     (?\n " ")
  547.     (?\( "\(\)")
  548.     (?\) "\)\(")
  549.     (?\\ "\\"))
  550.    (mail-extr-address-domain-literal-syntax-table
  551.     (?\000 ?\377 "w")
  552.     (?\040 " ")
  553.     (?\240 " ")
  554.     (?\t " ")
  555.     (?\r " ")
  556.     (?\n " ")
  557.     (?\[ "\(\]")            ;??????
  558.     (?\] "\)\[")            ;??????
  559.     (?\\ "\\"))
  560.    (mail-extr-address-text-comment-syntax-table
  561.     (?\000 ?\377 "w")
  562.     (?\040 " ")
  563.     (?\240 " ")
  564.     (?\t " ")
  565.     (?\r " ")
  566.     (?\n " ")
  567.     (?\( "\(\)")
  568.     (?\) "\)\(")
  569.     (?\[ "\(\]")
  570.     (?\] "\)\[")
  571.     (?\{ "\(\}")
  572.     (?\} "\)\{")
  573.     (?\\ "\\")
  574.     (?\" "\"")
  575.     ;; (?\' "\)\`")
  576.     ;; (?\` "\(\'")
  577.     )
  578.    (mail-extr-address-text-syntax-table
  579.     (?\000 ?\177 ".")
  580.     (?\200 ?\377 "w")
  581.     (?\040 " ")
  582.     (?\t " ")
  583.     (?\r " ")
  584.     (?\n " ")
  585.     (?A ?Z "w")
  586.     (?a ?z "w")
  587.     (?-    "w")
  588.     (?\}   "w")
  589.     (?\{   "w")
  590.     (?|    "w")
  591.     (?\'   "w")
  592.     (?~    "w")
  593.     (?0 ?9 "w"))
  594.    ))
  595.  
  596.  
  597. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  598. ;;
  599. ;; Utility functions and macros.
  600. ;;
  601.  
  602. (defmacro mail-extr-delete-char (n)
  603.   ;; in v19, delete-char is compiled as a function call, but delete-region
  604.   ;; is byte-coded, so it's much much faster.
  605.   (list 'delete-region '(point) (list '+ '(point) n)))
  606.  
  607. (defmacro mail-extr-skip-whitespace-forward ()
  608.   ;; v19 fn skip-syntax-forward is more tasteful, but not byte-coded.
  609.   '(skip-chars-forward " \t\n\r\240"))
  610.  
  611. (defmacro mail-extr-skip-whitespace-backward ()
  612.   ;; v19 fn skip-syntax-backward is more tasteful, but not byte-coded.
  613.   '(skip-chars-backward " \t\n\r\240"))
  614.  
  615.  
  616. (defmacro mail-extr-undo-backslash-quoting (beg end)
  617.   (`(save-excursion
  618.       (save-restriction
  619.     (narrow-to-region (, beg) (, end))
  620.     (goto-char (point-min))
  621.     ;; undo \ quoting
  622.     (while (search-forward "\\" nil t)
  623.       (mail-extr-delete-char -1)
  624.       (or (eobp)
  625.           (forward-char 1))
  626.       )))))
  627.  
  628. (defmacro mail-extr-nuke-char-at (pos)
  629.   (` (save-excursion
  630.        (goto-char (, pos))
  631.        (mail-extr-delete-char 1)
  632.        (insert ?\ ))))
  633.  
  634. (put 'mail-extr-nuke-outside-range
  635.      'edebug-form-spec '(symbolp &optional form form atom))
  636.  
  637. (defmacro mail-extr-nuke-outside-range (list-symbol
  638.                     beg-symbol end-symbol
  639.                     &optional no-replace)
  640.   ;; LIST-SYMBOL names a variable holding a list of buffer positions
  641.   ;; BEG-SYMBOL and END-SYMBOL name variables delimiting a range
  642.   ;; Each element of LIST-SYMBOL which lies outside of the range is
  643.   ;;  deleted from the list.
  644.   ;; Unless NO-REPLACE is true, at each of the positions in LIST-SYMBOL
  645.   ;;  which lie outside of the range, one character at that position is
  646.   ;;  replaced with a SPC.
  647.   (or (memq no-replace '(t nil))
  648.       (error "no-replace must be t or nil, evalable at macroexpand-time."))
  649.   (` (let ((temp (, list-symbol))
  650.        ch)
  651.        (while temp
  652.      (setq ch (car temp))
  653.      (cond ((or (> ch (, end-symbol))
  654.             (< ch (, beg-symbol)))
  655.         (,@ (if no-replace
  656.             nil
  657.               (` ((mail-extr-nuke-char-at ch)))))
  658.         (setcar temp nil)))
  659.      (setq temp (cdr temp)))
  660.        (setq (, list-symbol) (delq nil (, list-symbol))))))
  661.  
  662. (defun mail-extr-demarkerize (marker)
  663.   ;; if arg is a marker, destroys the marker, then returns the old value.
  664.   ;; otherwise returns the arg.
  665.   (if (markerp marker)
  666.       (let ((temp (marker-position marker)))
  667.     (set-marker marker nil)
  668.     temp)
  669.     marker))
  670.  
  671. (defun mail-extr-markerize (pos)
  672.   ;; coerces pos to a marker if non-nil.
  673.   (if (or (markerp pos) (null pos))
  674.       pos
  675.     (copy-marker pos)))
  676.  
  677. (defmacro mail-extr-last (list)
  678.   ;; Returns last element of LIST.
  679.   ;; Could be a subst.
  680.   (` (let ((list (, list)))
  681.        (while (not (null (cdr list)))
  682.      (setq list (cdr list)))
  683.        (car list))))
  684.   
  685. (defmacro mail-extr-safe-move-sexp (arg)
  686.   ;; Safely skip over one balanced sexp, if there is one.  Return t if success.
  687.   (` (condition-case error
  688.      (progn
  689.        (goto-char (scan-sexps (point) (, arg)))
  690.        t)
  691.        (error
  692.     ;; #### kludge kludge kludge kludge kludge kludge kludge !!!
  693.     (if (string-equal (nth 1 error) "Unbalanced parentheses")
  694.         nil
  695.       (while t
  696.         (signal (car error) (cdr error))))))))
  697.  
  698. (or (fboundp 'buffer-disable-undo) ;; v18 compat
  699.     (fset 'buffer-disable-undo 'buffer-flush-undo))
  700.  
  701.  
  702. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  703. ;;
  704. ;; The main function to grind addresses
  705. ;;
  706.  
  707. (defvar disable-initial-guessing-flag)    ; dynamic assignment
  708. (defvar cbeg)                ; dynamic assignment
  709. (defvar cend)                ; dynamic assignment
  710.  
  711. ;;;###autoload
  712. (defun mail-extract-address-components (address)
  713.   "Given an RFC-822 ADDRESS, extract full name and canonical address.
  714. Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).
  715. If no name can be extracted, FULL-NAME will be nil.
  716. ADDRESS may be a string or a buffer.  If it is a buffer, the visible 
  717.  (narrowed) portion of the buffer will be interpreted as the address.
  718.  (This feature exists so that the clever caller might be able to avoid
  719.  consing a string.)
  720. If ADDRESS contains more than one RFC-822 address, only the first is
  721.  returned.  Some day this function may be extended to extract multiple
  722.  addresses, or perhaps return the position at which parsing stopped."
  723.   (let ((canonicalization-buffer (get-buffer-create " *canonical address*"))
  724.     (extraction-buffer (get-buffer-create " *extract address components*"))
  725.     char
  726. ;;    multiple-addresses
  727.     <-pos >-pos @-pos colon-pos comma-pos !-pos %-pos \;-pos
  728.     group-colon-pos group-\;-pos route-addr-colon-pos
  729.     record-pos-symbol
  730.     first-real-pos last-real-pos
  731.     phrase-beg phrase-end
  732.     cbeg cend            ; dynamically set from -voodoo
  733.     quote-beg quote-end
  734.     atom-beg atom-end
  735.     mbox-beg mbox-end
  736.     \.-ends-name
  737.     temp
  738. ;;    name-suffix
  739.     fi mi li            ; first, middle, last initial
  740.     saved-%-pos saved-!-pos saved-@-pos
  741.     domain-pos \.-pos insert-point
  742. ;;    mailbox-name-processed-flag
  743.     disable-initial-guessing-flag    ; dynamically set from -voodoo
  744.     )
  745.     
  746.     (save-excursion
  747.       (set-buffer extraction-buffer)
  748.       (fundamental-mode)
  749.       (kill-all-local-variables)
  750.       (buffer-disable-undo extraction-buffer)
  751.       (set-syntax-table mail-extr-address-syntax-table)
  752.       (widen)
  753.       (erase-buffer)
  754.       (setq case-fold-search nil)
  755.       
  756.       ;; Insert extra space at beginning to allow later replacement with <
  757.       ;; without having to move markers.
  758.       (insert ?\ )
  759.  
  760.       ;; Insert the address itself.
  761.       (cond ((stringp address)
  762.          (insert address))
  763.         ((bufferp address)
  764.          (insert-buffer-substring address))
  765.         (t
  766.          (error "Illegal address: %s" address)))
  767.       
  768.       ;; stolen from rfc822.el
  769.       ;; Unfold multiple lines.
  770.       (goto-char (point-min))
  771.       (while (re-search-forward "\\([^\\]\\(\\\\\\\\\\)*\\)\n[ \t]" nil t)
  772.     (replace-match "\\1 " t))
  773.       
  774.       ;; first pass grabs useful information about address
  775.       (goto-char (point-min))
  776.       (while (progn
  777.            (mail-extr-skip-whitespace-forward)
  778.            (not (eobp)))
  779.     (setq char (char-after (point)))
  780.     (or first-real-pos
  781.         (if (not (eq char ?\())
  782.         (setq first-real-pos (point))))
  783.     (cond
  784.      ;; comment
  785.      ((eq char ?\()
  786.       (set-syntax-table mail-extr-address-comment-syntax-table)
  787.       ;; only record the first non-empty comment's position
  788.       (if (and (not cbeg)
  789.            (save-excursion
  790.              (forward-char 1)
  791.              (mail-extr-skip-whitespace-forward)
  792.              (not (eq ?\) (char-after (point))))))
  793.           (setq cbeg (point)))
  794.       ;; TODO: don't record if unbalanced
  795.       (or (mail-extr-safe-move-sexp 1)
  796.           (forward-char 1))
  797.       (set-syntax-table mail-extr-address-syntax-table)
  798.       (if (and cbeg
  799.            (not cend))
  800.           (setq cend (point))))
  801.      ;; quoted text
  802.      ((eq char ?\")
  803.       ;; only record the first non-empty quote's position
  804.       (if (and (not quote-beg)
  805.            (save-excursion
  806.              (forward-char 1)
  807.              (mail-extr-skip-whitespace-forward)
  808.              (not (eq ?\" (char-after (point))))))
  809.           (setq quote-beg (point)))
  810.       ;; TODO: don't record if unbalanced
  811.       (or (mail-extr-safe-move-sexp 1)
  812.           (forward-char 1))
  813.       (if (and quote-beg
  814.            (not quote-end))
  815.           (setq quote-end (point))))
  816.      ;; domain literals
  817.      ((eq char ?\[)
  818.       (set-syntax-table mail-extr-address-domain-literal-syntax-table)
  819.       (or (mail-extr-safe-move-sexp 1)
  820.           (forward-char 1))
  821.       (set-syntax-table mail-extr-address-syntax-table))
  822.      ;; commas delimit addresses when outside < > pairs.
  823.      ((and (eq char ?,)
  824.            (or (and (null <-pos)
  825.             ;; Handle ROUTE-ADDR address that is missing its <.
  826.             (not (eq ?@ (char-after (1+ (point))))))
  827.            (and >-pos
  828.             ;; handle weird munged addresses
  829.             ;; BUG FIX: This test was reversed.  Thanks to the
  830.             ;; brilliant Rod Whitby <rwhitby@research.canon.oz.au>
  831.             ;; for discovering this!
  832.             (< (mail-extr-last <-pos) (car >-pos)))))
  833. ;; It'd be great if some day this worked, but for now, punt.
  834. ;;      (setq multiple-addresses t)
  835. ;;      ;; *** Why do I want this:
  836. ;;      (mail-extr-delete-char 1)
  837. ;;      (narrow-to-region (point-min) (point))
  838.       (delete-region (point) (point-max))
  839.       (setq char ?\() ; HAVE I NO SHAME??
  840.       )
  841.      ;; record the position of various interesting chars, determine
  842.      ;; legality later.
  843.      ((setq record-pos-symbol
  844.         (cdr (assq char
  845.                '((?< . <-pos) (?> . >-pos) (?@ . @-pos)
  846.                  (?: . colon-pos) (?, . comma-pos) (?! . !-pos)
  847.                  (?% . %-pos) (?\; . \;-pos)))))
  848.       (set record-pos-symbol
  849.            (cons (point) (symbol-value record-pos-symbol)))
  850.       (forward-char 1))
  851.      ((eq char ?.)
  852.       (forward-char 1))
  853.      ((memq char '(
  854.                ;; comment terminator illegal
  855.                ?\)
  856.                ;; domain literal terminator illegal
  857.                ?\]
  858.                ;; \ allowed only within quoted strings,
  859.                ;; domain literals, and comments
  860.                ?\\
  861.                ))
  862.       (mail-extr-nuke-char-at (point))
  863.       (forward-char 1))
  864.      (t
  865.       (forward-word 1)))
  866.     (or (eq char ?\()
  867.         ;; At the end of first address of a multiple address header.
  868.         (and (eq char ?,)
  869.          (eobp))
  870.         (setq last-real-pos (point))))
  871.       
  872.       ;; Use only the leftmost <, if any.  Replace all others with spaces.
  873.       (while (cdr <-pos)
  874.     (mail-extr-nuke-char-at (car <-pos))
  875.     (setq <-pos (cdr <-pos)))
  876.       
  877.       ;; Use only the rightmost >, if any.  Replace all others with spaces.
  878.       (while (cdr >-pos)
  879.     (mail-extr-nuke-char-at (nth 1 >-pos))
  880.     (setcdr >-pos (nthcdr 2 >-pos)))
  881.       
  882.       ;; If multiple @s and a :, but no < and >, insert around buffer.
  883.       ;; Example: @foo.bar.dom,@xxx.yyy.zzz:mailbox@aaa.bbb.ccc
  884.       ;; This commonly happens on the UUCP "From " line.  Ugh.
  885.       (cond ((and (> (length @-pos) 1)
  886.           (eq 1 (length colon-pos))    ;TODO: check if between last two @s
  887.           (not \;-pos)
  888.           (not <-pos))
  889.          (goto-char (point-min))
  890.          (mail-extr-delete-char 1)
  891.          (setq <-pos (list (point)))
  892.          (insert ?<)))
  893.       
  894.       ;; If < but no >, insert > in rightmost possible position
  895.       (cond ((and <-pos
  896.           (null >-pos))
  897.          (goto-char (point-max))
  898.          (setq >-pos (list (point)))
  899.          (insert ?>)))
  900.       
  901.       ;; If > but no <, replace > with space.
  902.       (cond ((and >-pos
  903.           (null <-pos))
  904.          (mail-extr-nuke-char-at (car >-pos))
  905.          (setq >-pos nil)))
  906.  
  907.       ;; Turn >-pos and <-pos into non-lists
  908.       (setq >-pos (car >-pos)
  909.         <-pos (car <-pos))
  910.       
  911.       ;; Trim other punctuation lists of items outside < > pair to handle
  912.       ;; stupid MTAs.
  913.       (cond (<-pos            ; don't need to check >-pos also
  914.          ;; handle bozo software that violates RFC 822 by sticking
  915.          ;; punctuation marks outside of a < > pair
  916.          (mail-extr-nuke-outside-range @-pos <-pos >-pos t)
  917.          ;; RFC 822 says nothing about these two outside < >, but
  918.          ;; remove those positions from the lists to make things
  919.          ;; easier.
  920.          (mail-extr-nuke-outside-range !-pos <-pos >-pos t)
  921.          (mail-extr-nuke-outside-range %-pos <-pos >-pos t)))
  922.       
  923.       ;; Check for : that indicates GROUP list and for : part of
  924.       ;; ROUTE-ADDR spec.
  925.       ;; Can't possibly be more than two :.  Nuke any extra.
  926.       (while colon-pos
  927.     (setq temp (car colon-pos)
  928.           colon-pos (cdr colon-pos))
  929.     (cond ((and <-pos >-pos
  930.             (> temp <-pos)
  931.             (< temp >-pos))
  932.            (if (or route-addr-colon-pos
  933.                (< (length @-pos) 2)
  934.                (> temp (car @-pos))
  935.                (< temp (nth 1 @-pos)))
  936.            (mail-extr-nuke-char-at temp)
  937.          (setq route-addr-colon-pos temp)))
  938.           ((or (not <-pos)
  939.            (and <-pos
  940.             (< temp <-pos)))
  941.            (setq group-colon-pos temp))))
  942.       
  943.       ;; Nuke any ; that is in or to the left of a < > pair or to the left
  944.       ;; of a GROUP starting :.  Also, there may only be one ;.
  945.       (while \;-pos
  946.     (setq temp (car \;-pos)
  947.           \;-pos (cdr \;-pos))
  948.     (cond ((and <-pos >-pos
  949.             (> temp <-pos)
  950.             (< temp >-pos))
  951.            (mail-extr-nuke-char-at temp))
  952.           ((and (or (not group-colon-pos)
  953.             (> temp group-colon-pos))
  954.             (not group-\;-pos))
  955.            (setq group-\;-pos temp))))
  956.       
  957.       ;; Nuke unmatched GROUP syntax characters.
  958.       (cond ((and group-colon-pos (not group-\;-pos))
  959.          ;; *** Do I really need to erase it?
  960.          (mail-extr-nuke-char-at group-colon-pos)
  961.          (setq group-colon-pos nil)))
  962.       (cond ((and group-\;-pos (not group-colon-pos))
  963.          ;; *** Do I really need to erase it?
  964.          (mail-extr-nuke-char-at group-\;-pos)
  965.          (setq group-\;-pos nil)))
  966.       
  967.       ;; Handle junk like ";@host.company.dom" that sendmail adds.
  968.       ;; **** should I remember comment positions?
  969.       (cond
  970.        (group-\;-pos
  971.     ;; this is fine for now
  972.     (mail-extr-nuke-outside-range !-pos group-colon-pos group-\;-pos t)
  973.     (mail-extr-nuke-outside-range @-pos group-colon-pos group-\;-pos t)
  974.     (mail-extr-nuke-outside-range %-pos group-colon-pos group-\;-pos t)
  975.     (mail-extr-nuke-outside-range comma-pos group-colon-pos group-\;-pos t)
  976.     (and last-real-pos
  977.          (> last-real-pos (1+ group-\;-pos))
  978.          (setq last-real-pos (1+ group-\;-pos)))
  979.     ;; *** This may be wrong:
  980.         (and cend
  981.              (> cend group-\;-pos)
  982.              (setq cend nil
  983.                    cbeg nil))
  984.     (and quote-end
  985.          (> quote-end group-\;-pos)
  986.          (setq quote-end nil
  987.            quote-beg nil))
  988.     ;; This was both wrong and unnecessary:
  989.     ;;(narrow-to-region (point-min) group-\;-pos)
  990.  
  991.     ;; *** The entire handling of GROUP addresses seems rather lame.
  992.     ;; *** It deserves a complete rethink, except that these addresses
  993.     ;; *** are hardly ever seen.
  994.     ))
  995.       
  996.       ;; Any commas must be between < and : of ROUTE-ADDR.  Nuke any
  997.       ;; others.
  998.       ;; Hell, go ahead an nuke all of the commas.
  999.       ;; **** This will cause problems when we start handling commas in
  1000.       ;; the PHRASE part .... no it won't ... yes it will ... ?????
  1001.       (mail-extr-nuke-outside-range comma-pos 1 1)
  1002.       
  1003.       ;; can only have multiple @s inside < >.  The fact that some MTAs
  1004.       ;; put de-bracketed ROUTE-ADDRs in the UUCP-style "From " line is
  1005.       ;; handled above.
  1006.       
  1007.       ;; Locate PHRASE part of ROUTE-ADDR.
  1008.       (cond (<-pos
  1009.          (goto-char <-pos)
  1010.          (mail-extr-skip-whitespace-backward)
  1011.          (setq phrase-end (point))
  1012.          (goto-char (or ;;group-colon-pos
  1013.                 (point-min)))
  1014.          (mail-extr-skip-whitespace-forward)
  1015.          (if (< (point) phrase-end)
  1016.          (setq phrase-beg (point))
  1017.            (setq phrase-end nil))))
  1018.       
  1019.       ;; handle ROUTE-ADDRS with real ROUTEs.
  1020.       ;; If there are multiple @s, then we assume ROUTE-ADDR syntax, and
  1021.       ;; any % or ! must be semantically meaningless.
  1022.       ;; TODO: do this processing into canonicalization buffer
  1023.       (cond (route-addr-colon-pos
  1024.          (setq !-pos nil
  1025.            %-pos nil
  1026.            >-pos (copy-marker >-pos)
  1027.            route-addr-colon-pos (copy-marker route-addr-colon-pos))
  1028.          (goto-char >-pos)
  1029.          (insert-before-markers ?X)
  1030.          (goto-char (car @-pos))
  1031.          (while (setq @-pos (cdr @-pos))
  1032.            (mail-extr-delete-char 1)
  1033.            (setq %-pos (cons (point-marker) %-pos))
  1034.            (insert "%")
  1035.            (goto-char (1- >-pos))
  1036.            (save-excursion
  1037.          (insert-buffer-substring extraction-buffer
  1038.                       (car @-pos) route-addr-colon-pos)
  1039.          (delete-region (car @-pos) route-addr-colon-pos))
  1040.            (or (cdr @-pos)
  1041.            (setq saved-@-pos (list (point)))))
  1042.          (setq @-pos saved-@-pos)
  1043.          (goto-char >-pos)
  1044.          (mail-extr-delete-char -1)
  1045.          (mail-extr-nuke-char-at route-addr-colon-pos)
  1046.          (mail-extr-demarkerize route-addr-colon-pos)
  1047.          (setq route-addr-colon-pos nil
  1048.            >-pos (mail-extr-demarkerize >-pos)
  1049.            %-pos (mapcar 'mail-extr-demarkerize %-pos))))
  1050.       
  1051.       ;; de-listify @-pos
  1052.       (setq @-pos (car @-pos))
  1053.       
  1054.       ;; TODO: remove comments in the middle of an address
  1055.       
  1056.       (set-buffer canonicalization-buffer)
  1057.       (fundamental-mode)
  1058.       (kill-all-local-variables)
  1059.       (buffer-disable-undo canonicalization-buffer)
  1060.       (set-syntax-table mail-extr-address-syntax-table)
  1061.       (setq case-fold-search nil)
  1062.       
  1063.       (widen)
  1064.       (erase-buffer)
  1065.       (insert-buffer-substring extraction-buffer)
  1066.       
  1067.       (if <-pos
  1068.       (narrow-to-region (progn
  1069.                   (goto-char (1+ <-pos))
  1070.                   (mail-extr-skip-whitespace-forward)
  1071.                   (point))
  1072.                 >-pos)
  1073.     (if (and first-real-pos last-real-pos)
  1074.         (narrow-to-region first-real-pos last-real-pos)
  1075.       ;; ****** Oh no!  What if the address is completely empty!
  1076.       ;; *** Is this correct?
  1077.       (narrow-to-region (point-max) (point-max))
  1078.       ))
  1079.       
  1080.       (and @-pos %-pos
  1081.        (mail-extr-nuke-outside-range %-pos (point-min) @-pos))
  1082.       (and %-pos !-pos
  1083.        (mail-extr-nuke-outside-range !-pos (point-min) (car %-pos)))
  1084.       (and @-pos !-pos (not %-pos)
  1085.        (mail-extr-nuke-outside-range !-pos (point-min) @-pos))
  1086.       
  1087.       ;; Error condition:?? (and %-pos (not @-pos))
  1088.       
  1089.       ;; WARNING: THIS CODE IS DUPLICATED BELOW.
  1090.       (cond ((and %-pos
  1091.           (not @-pos))
  1092.          (goto-char (car %-pos))
  1093.          (mail-extr-delete-char 1)
  1094.          (setq @-pos (point))
  1095.          (insert "@")
  1096.          (setq %-pos (cdr %-pos))))
  1097.  
  1098.       (if mail-extr-mangle-uucp
  1099.       (cond (!-pos
  1100.          ;; **** I don't understand this save-restriction and the
  1101.          ;; narrow-to-region inside it.  Why did I do that?
  1102.          (save-restriction
  1103.            (cond ((and @-pos
  1104.                mail-extr-@-binds-tighter-than-!)
  1105.               (goto-char @-pos)
  1106.               (setq %-pos (cons (point) %-pos)
  1107.                 @-pos nil)
  1108.               (mail-extr-delete-char 1)
  1109.               (insert "%")
  1110.               (setq insert-point (point-max)))
  1111.              (mail-extr-@-binds-tighter-than-!
  1112.               (setq insert-point (point-max)))
  1113.              (%-pos
  1114.               (setq insert-point (mail-extr-last %-pos)
  1115.                 saved-%-pos (mapcar 'mail-extr-markerize %-pos)
  1116.                 %-pos nil
  1117.                 @-pos (mail-extr-markerize @-pos)))
  1118.              (@-pos
  1119.               (setq insert-point @-pos)
  1120.               (setq @-pos (mail-extr-markerize @-pos)))
  1121.              (t
  1122.               (setq insert-point (point-max))))
  1123.            (narrow-to-region (point-min) insert-point)
  1124.            (setq saved-!-pos (car !-pos))
  1125.            (while !-pos
  1126.          (goto-char (point-max))
  1127.          (cond ((and (not @-pos)
  1128.                  (not (cdr !-pos)))
  1129.             (setq @-pos (point))
  1130.             (insert-before-markers "@ "))
  1131.                (t
  1132.             (setq %-pos (cons (point) %-pos))
  1133.             (insert-before-markers "% ")))
  1134.          (backward-char 1)
  1135.          (insert-buffer-substring 
  1136.           (current-buffer)
  1137.           (if (nth 1 !-pos)
  1138.               (1+ (nth 1 !-pos))
  1139.             (point-min))
  1140.           (car !-pos))
  1141.          (mail-extr-delete-char 1)
  1142.          (or (save-excursion
  1143.                (mail-extr-safe-move-sexp -1)
  1144.                (mail-extr-skip-whitespace-backward)
  1145.                (eq ?. (preceding-char)))
  1146.              (insert-before-markers
  1147.               (if (save-excursion
  1148.                 (mail-extr-skip-whitespace-backward)
  1149.                 (eq ?. (preceding-char)))
  1150.               ""
  1151.             ".")
  1152.               "uucp"))
  1153.          (setq !-pos (cdr !-pos))))
  1154.          (and saved-%-pos
  1155.           (setq %-pos (append (mapcar 'mail-extr-demarkerize
  1156.                           saved-%-pos)
  1157.                       %-pos)))
  1158.          (setq @-pos (mail-extr-demarkerize @-pos))
  1159.          (narrow-to-region (1+ saved-!-pos) (point-max)))))
  1160.  
  1161.       ;; WARNING: THIS CODE IS DUPLICATED ABOVE.
  1162.       (cond ((and %-pos
  1163.           (not @-pos))
  1164.          (goto-char (car %-pos))
  1165.          (mail-extr-delete-char 1)
  1166.          (setq @-pos (point))
  1167.          (insert "@")
  1168.          (setq %-pos (cdr %-pos))))
  1169.  
  1170.       (setq %-pos (nreverse %-pos))
  1171.       ;; RFC 1034 doesn't approve of this, oh well:
  1172.       (downcase-region (or (car %-pos) @-pos (point-max)) (point-max))
  1173.       (cond (%-pos            ; implies @-pos valid
  1174.          (setq temp %-pos)
  1175.          (catch 'truncated
  1176.            (while temp
  1177.          (goto-char (or (nth 1 temp)
  1178.                 @-pos))
  1179.          (mail-extr-skip-whitespace-backward)
  1180.          (save-excursion
  1181.            (mail-extr-safe-move-sexp -1)
  1182.            (setq domain-pos (point))
  1183.            (mail-extr-skip-whitespace-backward)
  1184.            (setq \.-pos (eq ?. (preceding-char))))
  1185.          (cond ((and \.-pos
  1186.                  ;; #### string consing
  1187.                  (let ((s (intern-soft
  1188.                        (buffer-substring domain-pos (point))
  1189.                        all-top-level-domains)))
  1190.                    (and s (get s 'domain-name))))
  1191.             (narrow-to-region (point-min) (point))
  1192.             (goto-char (car temp))
  1193.             (mail-extr-delete-char 1)
  1194.             (setq @-pos (point))
  1195.             (setcdr temp nil)
  1196.             (setq %-pos (delq @-pos %-pos))
  1197.             (insert "@")
  1198.             (throw 'truncated t)))
  1199.          (setq temp (cdr temp))))))
  1200.       (setq mbox-beg (point-min)
  1201.         mbox-end (if %-pos (car %-pos)
  1202.                (or @-pos
  1203.                (point-max))))
  1204.       
  1205.       ;; Done canonicalizing address.
  1206.       
  1207.       (set-buffer extraction-buffer)
  1208.       
  1209.       ;; Decide what part of the address to search to find the full name.
  1210.       (cond (
  1211.          ;; Example: "First M. Last" <fml@foo.bar.dom>
  1212.          (and phrase-beg
  1213.           (eq quote-beg phrase-beg)
  1214.           (<= quote-end phrase-end))
  1215.          (narrow-to-region (1+ quote-beg) (1- quote-end))
  1216.          (mail-extr-undo-backslash-quoting (point-min) (point-max)))
  1217.  
  1218.         ;; Example: First Last <fml@foo.bar.dom>
  1219.         (phrase-beg
  1220.          (narrow-to-region phrase-beg phrase-end))
  1221.  
  1222.         ;; Example: fml@foo.bar.dom (First M. Last)
  1223.         (cbeg
  1224.          (narrow-to-region (1+ cbeg) (1- cend))
  1225.          (mail-extr-undo-backslash-quoting (point-min) (point-max))
  1226.          
  1227.          ;; Deal with spacing problems
  1228.          (goto-char (point-min))
  1229. ;         (cond ((not (search-forward " " nil t))
  1230. ;            (goto-char (point-min))
  1231. ;            (cond ((search-forward "_" nil t)
  1232. ;               ;; Handle the *idiotic* use of underlines as spaces.
  1233. ;               ;; Example: fml@foo.bar.dom (First_M._Last)
  1234. ;               (goto-char (point-min))
  1235. ;               (while (search-forward "_" nil t)
  1236. ;                 (replace-match " " t)))
  1237. ;              ((search-forward "." nil t)
  1238. ;               ;; Fix . used as space
  1239. ;               ;; Example: danj1@cb.att.com (daniel.jacobson)
  1240. ;               (goto-char (point-min))
  1241. ;               (while (re-search-forward mail-extr-bad-dot-pattern nil t)
  1242. ;                 (replace-match "\\1 \\2" t))))))
  1243.          )
  1244.         
  1245.         ;; Otherwise we try to get the name from the mailbox portion
  1246.         ;; of the address.
  1247.         ;; Example: First_M_Last@foo.bar.dom
  1248.         (t
  1249.          ;; *** Work in canon buffer instead?  No, can't.  Hmm.
  1250.          (goto-char (point-max))
  1251.          (narrow-to-region (point) (point))
  1252.          (insert-buffer-substring canonicalization-buffer
  1253.                       mbox-beg mbox-end)
  1254.          (goto-char (point-min))
  1255.          
  1256.          ;; Example: First_Last.XXX@foo.bar.dom
  1257.          (setq \.-ends-name (re-search-forward "[_0-9]" nil t))
  1258.          
  1259.          (goto-char (point-min))
  1260.  
  1261.          (if (not mail-extr-mangle-uucp)
  1262.          (modify-syntax-entry ?! "w" (syntax-table)))
  1263.  
  1264.          (while (progn
  1265.               (mail-extr-skip-whitespace-forward)
  1266.               (not (eobp)))
  1267.            (setq char (char-after (point)))
  1268.            (cond
  1269.         ((eq char ?\")
  1270.          (setq quote-beg (point))
  1271.          (or (mail-extr-safe-move-sexp 1)
  1272.              ;; TODO: handle this error condition!!!!!
  1273.              (forward-char 1))
  1274.          ;; take into account deletions
  1275.          (setq quote-end (- (point) 2))
  1276.          (save-excursion
  1277.            (backward-char 1)
  1278.            (mail-extr-delete-char 1)
  1279.            (goto-char quote-beg)
  1280.            (mail-extr-delete-char 1))
  1281.          (mail-extr-undo-backslash-quoting quote-beg quote-end)
  1282.          (or (eq ?\  (char-after (point)))
  1283.              (insert " "))
  1284. ;;         (setq mailbox-name-processed-flag t)
  1285.          (setq \.-ends-name t))
  1286.         ((eq char ?.)
  1287.          (if (memq (char-after (1+ (point))) '(?_ ?=))
  1288.              (progn
  1289.                (forward-char 1)
  1290.                (mail-extr-delete-char 1)
  1291.                (insert ?\ ))
  1292.            (if \.-ends-name
  1293.                (narrow-to-region (point-min) (point))
  1294.              (mail-extr-delete-char 1)
  1295.              (insert " ")))
  1296. ;;         (setq mailbox-name-processed-flag t)
  1297.          )
  1298.         ((memq (char-syntax char) '(?. ?\\))
  1299.          (mail-extr-delete-char 1)
  1300.          (insert " ")
  1301. ;;         (setq mailbox-name-processed-flag t)
  1302.          )
  1303.         (t
  1304.          (setq atom-beg (point))
  1305.          (forward-word 1)
  1306.          (setq atom-end (point))
  1307.          (goto-char atom-beg)
  1308.          (save-restriction
  1309.            (narrow-to-region atom-beg atom-end)
  1310.            (cond
  1311.             
  1312.             ;; Handle X.400 addresses encoded in RFC-822.
  1313.             ;; *** Shit!  This has to handle the case where it is
  1314.             ;; *** embedded in a quote too!
  1315.             ;; *** Shit!  The input is being broken up into atoms
  1316.             ;; *** by periods!
  1317.             ((looking-at mail-extr-x400-encoded-address-pattern)
  1318.              
  1319.              ;; Copy the contents of the individual fields that
  1320.              ;; might hold name data to the beginning.
  1321.              (mapcar
  1322.               (function
  1323.                (lambda (field-pattern)
  1324.              (cond
  1325.               ((save-excursion
  1326.                  (re-search-forward field-pattern nil t))
  1327.                (insert-buffer-substring (current-buffer)
  1328.                             (match-beginning 1)
  1329.                             (match-end 1))
  1330.                (insert " ")))))
  1331.               (list mail-extr-x400-encoded-address-given-name-pattern
  1332.                 mail-extr-x400-encoded-address-surname-pattern
  1333.                 mail-extr-x400-encoded-address-full-name-pattern))
  1334.              
  1335.              ;; Discard the rest, since it contains stuff like
  1336.              ;; routing information, not part of a name.
  1337.              (mail-extr-skip-whitespace-backward)
  1338.              (delete-region (point) (point-max))
  1339.              
  1340.              ;; Handle periods used for spacing.
  1341.              (while (re-search-forward mail-extr-bad-dot-pattern nil t)
  1342.                (replace-match "\\1 \\2" t))
  1343.              
  1344. ;;             (setq mailbox-name-processed-flag t)
  1345.              )
  1346.             
  1347.             ;; Handle normal addresses.
  1348.             (t
  1349.              (goto-char (point-min))
  1350.              ;; Handle _ and = used for spacing.
  1351.              (while (re-search-forward "\\([^_=]+\\)[_=]" nil t)
  1352.                (replace-match "\\1 " t)
  1353. ;;               (setq mailbox-name-processed-flag t)
  1354.                )
  1355.              (goto-char (point-max))))))))
  1356.  
  1357.          ;; undo the dirty deed
  1358.          (if (not mail-extr-mangle-uucp)
  1359.          (modify-syntax-entry ?! "." (syntax-table)))
  1360.          ;;
  1361.          ;; If we derived the name from the mailbox part of the address,
  1362.          ;; and we only got one word out of it, don't treat that as a
  1363.          ;; name.  "foo@bar" --> (nil "foo@bar"), not ("foo" "foo@bar")
  1364.              ;; (if (not mailbox-name-processed-flag)
  1365.              ;;     (delete-region (point-min) (point-max)))
  1366.          ))
  1367.       
  1368.       (set-syntax-table mail-extr-address-text-syntax-table)
  1369.       
  1370.       (mail-extr-voodoo mbox-beg mbox-end canonicalization-buffer)
  1371.       (goto-char (point-min))
  1372.  
  1373.       ;; If name is "First Last" and userid is "F?L", then assume
  1374.       ;; the middle initial is the second letter in the userid.
  1375.       ;; Initial code by Jamie Zawinski <jwz@lucid.com>
  1376.       ;; *** Make it work when there's a suffix as well.
  1377.       (goto-char (point-min))
  1378.       (cond ((and mail-extr-guess-middle-initial
  1379.           (not disable-initial-guessing-flag)
  1380.           (eq 3 (- mbox-end mbox-beg))
  1381.           (progn
  1382.             (goto-char (point-min))
  1383.             (looking-at mail-extr-two-name-pattern)))
  1384.          (setq fi (char-after (match-beginning 0))
  1385.            li (char-after (match-beginning 3)))
  1386.          (save-excursion
  1387.            (set-buffer canonicalization-buffer)
  1388.            ;; char-equal is ignoring case here, so no need to upcase
  1389.            ;; or downcase.
  1390.            (let ((case-fold-search t))
  1391.          (and (char-equal fi (char-after mbox-beg))
  1392.               (char-equal li (char-after (1- mbox-end)))
  1393.               (setq mi (char-after (1+ mbox-beg))))))
  1394.          (cond ((and mi
  1395.              ;; TODO: use better table than syntax table
  1396.              (eq ?w (char-syntax mi)))
  1397.             (goto-char (match-beginning 3))
  1398.             (insert (upcase mi) ". ")))))
  1399.       
  1400.       ;; Nuke name if it is the same as mailbox name.
  1401.       (let ((buffer-length (- (point-max) (point-min)))
  1402.         (i 0)
  1403.         (names-match-flag t))
  1404.     (cond ((and (> buffer-length 0)
  1405.             (eq buffer-length (- mbox-end mbox-beg)))
  1406.            (goto-char (point-max))
  1407.            (insert-buffer-substring canonicalization-buffer
  1408.                     mbox-beg mbox-end)
  1409.            (while (and names-match-flag
  1410.                (< i buffer-length))
  1411.          (or (eq (downcase (char-after (+ i (point-min))))
  1412.              (downcase
  1413.               (char-after (+ i buffer-length (point-min)))))
  1414.              (setq names-match-flag nil))
  1415.          (setq i (1+ i)))
  1416.            (delete-region (+ (point-min) buffer-length) (point-max))
  1417.            (if names-match-flag
  1418.            (narrow-to-region (point) (point))))))
  1419.       
  1420.       ;; Nuke name if it's just one word.
  1421.       (goto-char (point-min))
  1422.       (and mail-extr-ignore-single-names
  1423.        (not (re-search-forward "[- ]" nil t))
  1424.        (narrow-to-region (point) (point)))
  1425.       
  1426.       ;; Result
  1427.       (list (if (not (= (point-min) (point-max)))
  1428.         (buffer-string))
  1429.         (progn
  1430.           (set-buffer canonicalization-buffer)
  1431.           (if (not (= (point-min) (point-max)))
  1432.           (buffer-string))))
  1433.       )))
  1434.  
  1435. (defun mail-extr-voodoo (mbox-beg mbox-end canonicalization-buffer)
  1436.   (let ((word-count 0)
  1437.     (case-fold-search nil)
  1438.     mixed-case-flag lower-case-flag ;;upper-case-flag
  1439.     suffix-flag last-name-comma-flag
  1440.     ;;cbeg cend
  1441.     initial
  1442.     begin-again-flag
  1443.     drop-this-word-if-trailing-flag
  1444.     drop-last-word-if-trailing-flag
  1445.     word-found-flag
  1446.     this-word-beg last-word-beg
  1447.     name-beg name-end
  1448.     name-done-flag
  1449.     )
  1450.     (save-excursion
  1451.       (set-syntax-table mail-extr-address-text-syntax-table)
  1452.       
  1453.       ;; This was moved above.
  1454.       ;; Fix . used as space
  1455.       ;; But it belongs here because it occurs not only as
  1456.       ;;   rypens@reks.uia.ac.be (Piet.Rypens)
  1457.       ;; but also as
  1458.       ;;   "Piet.Rypens" <rypens@reks.uia.ac.be>
  1459.       ;;(goto-char (point-min))
  1460.       ;;(while (re-search-forward mail-extr-bad-dot-pattern nil t)
  1461.       ;;  (replace-match "\\1 \\2" t))
  1462.  
  1463.       (cond ((not (search-forward " " nil t))
  1464.          (goto-char (point-min))
  1465.          (cond ((search-forward "_" nil t)
  1466.             ;; Handle the *idiotic* use of underlines as spaces.
  1467.             ;; Example: fml@foo.bar.dom (First_M._Last)
  1468.             (goto-char (point-min))
  1469.             (while (search-forward "_" nil t)
  1470.               (replace-match " " t)))
  1471.            ((search-forward "." nil t)
  1472.             ;; Fix . used as space
  1473.             ;; Example: danj1@cb.att.com (daniel.jacobson)
  1474.             (goto-char (point-min))
  1475.             (while (re-search-forward mail-extr-bad-dot-pattern nil t)
  1476.               (replace-match "\\1 \\2" t))))))
  1477.  
  1478.  
  1479.       ;; Loop over the words (and other junk) in the name.
  1480.       (goto-char (point-min))
  1481.       (while (not name-done-flag)
  1482.     
  1483.     (cond (word-found-flag
  1484.            ;; Last time through this loop we skipped over a word.
  1485.            (setq last-word-beg this-word-beg)
  1486.            (setq drop-last-word-if-trailing-flag
  1487.              drop-this-word-if-trailing-flag)
  1488.            (setq word-found-flag nil)))
  1489.  
  1490.     (cond (begin-again-flag
  1491.            ;; Last time through the loop we found something that
  1492.            ;; indicates we should pretend we are beginning again from
  1493.            ;; the start.
  1494.            (setq word-count 0)
  1495.            (setq last-word-beg nil)
  1496.            (setq drop-last-word-if-trailing-flag nil)
  1497.            (setq mixed-case-flag nil)
  1498.            (setq lower-case-flag nil)
  1499. ;;           (setq upper-case-flag nil)
  1500.            (setq begin-again-flag nil)
  1501.            ))
  1502.     
  1503.     ;; Initialize for this iteration of the loop.
  1504.     (mail-extr-skip-whitespace-forward)
  1505.     (if (eq word-count 0) (narrow-to-region (point) (point-max)))
  1506.     (setq this-word-beg (point))
  1507.     (setq drop-this-word-if-trailing-flag nil)
  1508.     
  1509.     ;; Decide what to do based on what we are looking at.
  1510.     (cond
  1511.      
  1512.      ;; Delete title
  1513.      ((and (eq word-count 0)
  1514.            (looking-at mail-extr-full-name-prefixes))
  1515.       (goto-char (match-end 0))
  1516.       (narrow-to-region (point) (point-max)))
  1517.      
  1518.      ;; Stop after name suffix
  1519.      ((and (>= word-count 2)
  1520.            (looking-at mail-extr-full-name-suffix-pattern))
  1521.       (mail-extr-skip-whitespace-backward)
  1522.       (setq suffix-flag (point))
  1523.       (if (eq ?, (following-char))
  1524.           (forward-char 1)
  1525.         (insert ?,))
  1526.       ;; Enforce at least one space after comma
  1527.       (or (eq ?\  (following-char))
  1528.           (insert ?\ ))
  1529.       (mail-extr-skip-whitespace-forward)
  1530.       (cond ((memq (following-char) '(?j ?J ?s ?S))
  1531.          (capitalize-word 1)
  1532.          (if (eq (following-char) ?.)
  1533.              (forward-char 1)
  1534.            (insert ?.)))
  1535.         (t
  1536.          (upcase-word 1)))
  1537.       (setq word-found-flag t)
  1538.       (setq name-done-flag t))
  1539.      
  1540.      ;; Handle SCA names
  1541.      ((looking-at "MKA \\(.+\\)")    ; "Mundanely Known As"
  1542.       (goto-char (match-beginning 1))
  1543.       (narrow-to-region (point) (point-max))
  1544.       (setq begin-again-flag t))
  1545.      
  1546.      ;; Check for initial last name followed by comma
  1547.      ((and (eq ?, (following-char))
  1548.            (eq word-count 1))
  1549.       (forward-char 1)
  1550.       (setq last-name-comma-flag t)
  1551.       (or (eq ?\  (following-char))
  1552.           (insert ?\ )))
  1553.      
  1554.      ;; Stop before trailing comma-separated comment
  1555.      ;; THIS CASE MUST BE AFTER THE PRECEDING CASES.
  1556.      ;; *** This case is redundant???
  1557.      ;;((eq ?, (following-char))
  1558.      ;; (setq name-done-flag t))
  1559.      
  1560.      ;; Delete parenthesized/quoted comment/nickname
  1561.      ((memq (following-char) '(?\( ?\{ ?\[ ?\" ?\' ?\`))
  1562.       (setq cbeg (point))
  1563.       (set-syntax-table mail-extr-address-text-comment-syntax-table)
  1564.       (cond ((memq (following-char) '(?\' ?\`))
  1565.          (or (search-forward "'" nil t
  1566.                      (if (eq ?\' (following-char)) 2 1))
  1567.              (mail-extr-delete-char 1)))
  1568.         (t
  1569.          (or (mail-extr-safe-move-sexp 1)
  1570.              (goto-char (point-max)))))
  1571.       (set-syntax-table mail-extr-address-text-syntax-table)
  1572.       (setq cend (point))
  1573.       (cond
  1574.        ;; Handle case of entire name being quoted
  1575.        ((and (eq word-count 0)
  1576.          (looking-at " *\\'")
  1577.          (>= (- cend cbeg) 2))
  1578.         (narrow-to-region (1+ cbeg) (1- cend))
  1579.         (goto-char (point-min)))
  1580.        (t
  1581.         ;; Handle case of quoted initial
  1582.         (if (and (or (= 3 (- cend cbeg))
  1583.              (and (= 4 (- cend cbeg))
  1584.                   (eq ?. (char-after (+ 2 cbeg)))))
  1585.              (not (looking-at " *\\'")))
  1586.         (setq initial (char-after (1+ cbeg)))
  1587.           (setq initial nil))
  1588.         (delete-region cbeg cend)
  1589.         (if initial
  1590.         (insert initial ". ")))))
  1591.      
  1592.      ;; Handle & substitution
  1593.      ((and (or (bobp)
  1594.            (eq ?\  (preceding-char)))
  1595.            (looking-at "&\\( \\|\\'\\)"))
  1596.       (mail-extr-delete-char 1)
  1597.       (capitalize-region
  1598.        (point)
  1599.        (progn
  1600.          (insert-buffer-substring canonicalization-buffer
  1601.                       mbox-beg mbox-end)
  1602.          (point)))
  1603.       (setq disable-initial-guessing-flag t)
  1604.       (setq word-found-flag t))
  1605.      
  1606.      ;; Handle *Stupid* VMS date stamps
  1607.      ((looking-at mail-extr-stupid-vms-date-stamp-pattern)
  1608.       (replace-match "" t))
  1609.      
  1610.      ;; Handle Chinese characters.
  1611.      ((looking-at mail-extr-hz-embedded-gb-encoded-chinese-pattern)
  1612.       (goto-char (match-end 0))
  1613.       (setq word-found-flag t))
  1614.      
  1615.      ;; Skip initial garbage characters.
  1616.      ;; THIS CASE MUST BE AFTER THE PRECEDING CASES.
  1617.      ((and (eq word-count 0)
  1618.            (looking-at mail-extr-leading-garbage))
  1619.       (goto-char (match-end 0))
  1620.       ;; *** Skip backward over these???
  1621.       ;; (skip-chars-backward "& \"")
  1622.       (narrow-to-region (point) (point-max)))
  1623.      
  1624.      ;; Various stopping points
  1625.      ((or
  1626.        
  1627.        ;; Stop before ALL CAPS acronyms, if preceded by mixed-case
  1628.        ;; words.  Example: XT-DEM.
  1629.        (and (>= word-count 2)
  1630.         mixed-case-flag
  1631.         (looking-at mail-extr-weird-acronym-pattern)
  1632.         (not (looking-at mail-extr-roman-numeral-pattern)))
  1633.        
  1634.        ;; Stop before trailing alternative address
  1635.        (looking-at mail-extr-alternative-address-pattern)
  1636.        
  1637.        ;; Stop before trailing comment not introduced by comma
  1638.        ;; THIS CASE MUST BE AFTER AN EARLIER CASE.
  1639.        (looking-at mail-extr-trailing-comment-start-pattern)
  1640.        
  1641.        ;; Stop before telephone numbers
  1642.        (looking-at mail-extr-telephone-extension-pattern))
  1643.       (setq name-done-flag t))
  1644.      
  1645.      ;; Delete ham radio call signs
  1646.      ((looking-at mail-extr-ham-call-sign-pattern)
  1647.       (delete-region (match-beginning 0) (match-end 0)))
  1648.      
  1649.      ;; Fixup initials
  1650.      ((looking-at mail-extr-initial-pattern)
  1651.       (or (eq (following-char) (upcase (following-char)))
  1652.           (setq lower-case-flag t))
  1653.       (forward-char 1)
  1654.       (if (eq ?. (following-char))
  1655.           (forward-char 1)
  1656.         (insert ?.))
  1657.       (or (eq ?\  (following-char))
  1658.           (insert ?\ ))
  1659.       (setq word-found-flag t))
  1660.      
  1661.      ;; Handle BITNET LISTSERV list names.
  1662.      ((and (eq word-count 0)
  1663.            (looking-at mail-extr-listserv-list-name-pattern))
  1664.       (narrow-to-region (match-beginning 1) (match-end 1))
  1665.       (setq word-found-flag t)
  1666.       (setq name-done-flag t))
  1667.      
  1668.      ;; Regular name words
  1669.      ((looking-at mail-extr-name-pattern)
  1670.       (setq name-beg (point))
  1671.       (setq name-end (match-end 0))
  1672.       
  1673.       ;; Certain words will be dropped if they are at the end.
  1674.       (and (>= word-count 2)
  1675.            (not lower-case-flag)
  1676.            (or
  1677.         ;; A trailing 4-or-more letter lowercase words preceded by
  1678.         ;; mixed case or uppercase words will be dropped.
  1679.         (looking-at "[a-z][a-z][a-z][a-z]+[ \t]*\\'")
  1680.         ;; Drop a trailing word which is terminated with a period.
  1681.         (eq ?. (char-after (1- name-end))))
  1682.            (setq drop-this-word-if-trailing-flag t))
  1683.       
  1684.       ;; Set the flags that indicate whether we have seen a lowercase
  1685.       ;; word, a mixed case word, and an uppercase word.
  1686.       (if (re-search-forward "[a-z]" name-end t)
  1687.           (if (progn
  1688.             (goto-char name-beg)
  1689.             (re-search-forward "[A-Z]" name-end t))
  1690.           (setq mixed-case-flag t)
  1691.         (setq lower-case-flag t))
  1692. ;;        (setq upper-case-flag t)
  1693.         )
  1694.       
  1695.       (goto-char name-end)
  1696.       (setq word-found-flag t))
  1697.  
  1698.      (t
  1699.       (setq name-done-flag t)
  1700.       ))
  1701.     
  1702.     ;; Count any word that we skipped over.
  1703.     (if word-found-flag
  1704.         (setq word-count (1+ word-count))))
  1705.       
  1706.       ;; If the last thing in the name is 2 or more periods, or one or more
  1707.       ;; other sentence terminators (but not a single period) then keep them
  1708.       ;; and the preceeding word.  This is for the benefit of whole sentences
  1709.       ;; in the name field: it's better behavior than dropping the last word
  1710.       ;; of the sentence...
  1711.       (if (and (not suffix-flag)
  1712.            (looking-at "\\(\\.+\\|[?!;:.][?!;:.]+\\|[?!;:][?!;:.]*\\)\\'"))
  1713.       (goto-char (setq suffix-flag (point-max))))
  1714.  
  1715.       ;; Drop everything after point and certain trailing words.
  1716.       (narrow-to-region (point-min)
  1717.             (or (and drop-last-word-if-trailing-flag
  1718.                  last-word-beg)
  1719.                 (point)))
  1720.       
  1721.       ;; Xerox's mailers SUCK!!!!!!
  1722.       ;; We simply refuse to believe that any last name is PARC or ADOC.
  1723.       ;; If it looks like that is the last name, that there is no meaningful
  1724.       ;; here at all.  Actually I guess it would be best to map patterns
  1725.       ;; like foo.hoser@xerox.com into foo@hoser.xerox.com, but I don't
  1726.       ;; actually know that that is what's going on.
  1727.       (cond ((not suffix-flag)
  1728.          (goto-char (point-min))
  1729.          (let ((case-fold-search t))
  1730.            (if (looking-at "[-A-Za-z_]+[. ]\\(PARC\\|ADOC\\)\\'")
  1731.            (erase-buffer)))))
  1732.  
  1733.       ;; If last name first put it at end (but before suffix)
  1734.       (cond (last-name-comma-flag
  1735.          (goto-char (point-min))
  1736.          (search-forward ",")
  1737.          (setq name-end (1- (point)))
  1738.          (goto-char (or suffix-flag (point-max)))
  1739.          (or (eq ?\  (preceding-char))
  1740.          (insert ?\ ))
  1741.          (insert-buffer-substring (current-buffer) (point-min) name-end)
  1742.          (goto-char name-end)
  1743.          (skip-chars-forward "\t ,")
  1744.          (narrow-to-region (point) (point-max))))
  1745.       
  1746.       ;; Delete leading and trailing junk characters.
  1747.       ;; *** This is probably completly unneeded now.
  1748.       ;;(goto-char (point-max))
  1749.       ;;(skip-chars-backward mail-extr-non-end-name-chars)
  1750.       ;;(if (eq ?. (following-char))
  1751.       ;;    (forward-char 1))
  1752.       ;;(narrow-to-region (point)
  1753.       ;;                  (progn
  1754.       ;;                    (goto-char (point-min))
  1755.       ;;                    (skip-chars-forward mail-extr-non-begin-name-chars)
  1756.       ;;                    (point)))
  1757.       
  1758.       ;; Compress whitespace
  1759.       (goto-char (point-min))
  1760.       (while (re-search-forward "[ \t\n]+" nil t)
  1761.     (replace-match (if (eobp) "" " ") t))
  1762.       )))
  1763.  
  1764.  
  1765.  
  1766. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1767. ;;
  1768. ;; Table of top-level domain names.
  1769. ;;
  1770. ;; This is used during address canonicalization; be careful of format changes.
  1771. ;; Keep in mind that the country abbreviations follow ISO-3166.  There is
  1772. ;; a U.S. FIPS that specifies a different set of two-letter country
  1773. ;; abbreviations.
  1774.  
  1775. (defconst all-top-level-domains
  1776.   (let ((ob (make-vector 509 0)))
  1777.     (mapcar
  1778.      (function
  1779.       (lambda (x)
  1780.     (put (intern (downcase (car x)) ob)
  1781.          'domain-name
  1782.          (if (nth 2 x)
  1783.          (format (nth 2 x) (nth 1 x))
  1784.            (nth 1 x)))))
  1785.      '(("ag" "Antigua")
  1786.        ("ar" "Argentina"    "Argentine Republic")
  1787.        ("arpa" t        "Advanced Projects Research Agency")
  1788.        ("at" "Austria"        "The Republic of %s")
  1789.        ("au" "Australia")
  1790.        ("bb" "Barbados")
  1791.        ("be" "Belgium"        "The Kingdom of %s")
  1792.        ("bg" "Bulgaria")
  1793.        ("bitnet" t        "Because It's Time NET")
  1794.        ("bo" "Bolivia"        "Republic of %s")
  1795.        ("br" "Brazil"        "The Federative Republic of %s")
  1796.        ("bs" "Bahamas")
  1797.        ("bz" "Belize")
  1798.        ("ca" "Canada")
  1799.        ("ch" "Switzerland"    "The Swiss Confederation")
  1800.        ("cl" "Chile"        "The Republic of %s")
  1801.        ("cn" "China"        "The People's Republic of %s")
  1802.        ("co" "Columbia")
  1803.        ("com" t            "Commercial")
  1804.        ("cr" "Costa Rica"    "The Republic of %s")
  1805.        ("cs" "Czechoslovakia")
  1806.        ("de" "Germany")
  1807.        ("dk" "Denmark")
  1808.        ("dm" "Dominica")
  1809.        ("do" "Dominican Republic"    "The %s")
  1810.        ("ec" "Ecuador"        "The Republic of %s")
  1811.        ("edu" t            "Educational")
  1812.        ("eg" "Egypt"        "The Arab Republic of %s")
  1813.        ("es" "Spain"        "The Kingdom of %s")
  1814.        ("fi" "Finland"        "The Republic of %s")
  1815.        ("fj" "Fiji")
  1816.        ("fr" "France")
  1817.        ("gov" t            "Government (U.S.A.)")
  1818.        ("gr" "Greece"        "The Hellenic Republic (%s)")
  1819.        ("hk" "Hong Kong")
  1820.        ("hu" "Hungary"        "The Hungarian People's Republic")    ;???
  1821.        ("ie" "Ireland")
  1822.        ("il" "Israel"        "The State of %s")
  1823.        ("in" "India"        "The Republic of %s")
  1824.        ("int" t            "(something British, don't know what)")
  1825.        ("is" "Iceland"        "The Republic of %s")
  1826.        ("it" "Italy"        "The Italian Republic")
  1827.        ("jm" "Jamaica")
  1828.        ("jp" "Japan")
  1829.        ("kn" "St. Kitts and Nevis")
  1830.        ("kr" "South Korea")
  1831.        ("lc" "St. Lucia")
  1832.        ("lk" "Sri Lanka"    "The Democratic Socialist Republic of %s")
  1833.        ("mil" t            "Military (U.S.A.)")
  1834.        ("mx" "Mexico"        "The United Mexican States")
  1835.        ("my" "Malaysia"        "%s (changed to Myanmar?)")        ;???
  1836.        ("na" "Namibia")
  1837.        ("nato" t        "North Atlantic Treaty Organization")
  1838.        ("net" t            "Network")
  1839.        ("ni" "Nicaragua"    "The Republic of %s")
  1840.        ("nl" "Netherlands"    "The Kingdom of the %s")
  1841.        ("no" "Norway"        "The Kingdom of %s")
  1842.        ("nz" "New Zealand")
  1843.        ("org" t            "Organization")
  1844.        ("pe" "Peru")
  1845.        ("pg" "Papua New Guinea")
  1846.        ("ph" "Philippines"    "The Republic of the %s")
  1847.        ("pl" "Poland")
  1848.        ("pr" "Puerto Rico")
  1849.        ("pt" "Portugal"        "The Portugese Republic")
  1850.        ("py" "Paraguay")
  1851.        ("se" "Sweden"        "The Kingdom of %s")
  1852.        ("sg" "Singapore"    "The Republic of %s")
  1853.        ("sr" "Suriname")
  1854.        ("su" "Soviet Union")
  1855.        ("th" "Thailand"        "The Kingdom of %s")
  1856.        ("tn" "Tunisia")
  1857.        ("tr" "Turkey"        "The Republic of %s")
  1858.        ("tt" "Trinidad and Tobago")
  1859.        ("tw" "Taiwan")
  1860.        ("uk" "United Kingdom"    "The %s of Great Britain")
  1861.        ("unter-dom" t        "(something German)")
  1862.        ("us" "U.S.A."        "The United States of America")
  1863.        ("uucp" t        "Unix to Unix CoPy")
  1864.        ("uy" "Uruguay"        "The Eastern Republic of %s")
  1865.        ("vc" "St. Vincent and the Grenadines")
  1866.        ("ve" "Venezuela"    "The Republic of %s")
  1867.        ("yu" "Yugoslavia"    "The Socialist Federal Republic of %s")
  1868.        ;; Also said to be Zambia ... (why not Zaire???)
  1869.        ("za" "South Africa"    "The Republic of %s (or Zambia? Zaire?)")
  1870.        ("zw" "Zimbabwe"        "Republic of %s")
  1871. ;; fipnet
  1872.        ))
  1873.     ob))
  1874.  
  1875. ;;;###autoload
  1876. (defun what-domain (x)
  1877.   "Prompts for a mail domain, and prints the country it corresponds to
  1878. in the minibuffer."
  1879.   (interactive
  1880.    (let ((completion-ignore-case t))
  1881.      (list (completing-read "Domain: " all-top-level-domains nil t))))
  1882.   (or (setq x (intern-soft (downcase x) all-top-level-domains))
  1883.       (error "no such domain"))
  1884.   (message "%s: %s" (upcase (symbol-name x)) (get x 'domain-name)))
  1885.  
  1886.  
  1887. ;(let ((all nil))
  1888. ;  (mapatoms #'(lambda (x)
  1889. ;        (if (and (boundp x) 
  1890. ;             (string-match "^mail-extr-" (symbol-name x)))
  1891. ;            (setq all (cons x all)))))
  1892. ;  (setq all (sort all #'string-lessp))
  1893. ;  (cons 'setq
  1894. ;    (apply 'nconc (mapcar #'(lambda (x)
  1895. ;                  (list x (symbol-value x)))
  1896. ;                  all))))
  1897.  
  1898.  
  1899. (provide 'mail-extr)
  1900.  
  1901. ;;; mail-extr.el ends here
  1902.